package com.heima.account.action;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.account.entity.Account;
import com.heima.account.entity.AccountFreeze;
import com.heima.account.service.IAccountFreezeService;
import com.heima.account.service.IAccountService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author WSJ
 * @Date 2022-03-08-15:55
 * @Version 1.0 （版本号）
 */
@Service
public class AccountActionImpl implements AccountAction {
    @Autowired
    private IAccountFreezeService freezeService;

    @Autowired
    private IAccountService accountService;
    @Override
    public void deduct(Integer userId, Integer money) {
        //用户账户金额减少
        LambdaUpdateWrapper<Account> update=new LambdaUpdateWrapper<>();
        update.eq(Account::getUserId,userId);
        update.setSql("money=money-"+money);
        accountService.update(update);
        //冻结金额增加
        AccountFreeze accountFreeze = new AccountFreeze();
        accountFreeze.setFreezeMoney(money);
        accountFreeze.setUserId(userId);
        accountFreeze.setXid(RootContext.getXID());
        freezeService.save(accountFreeze);
    }

    @Override
    public boolean confirm(BusinessActionContext context) {
        //成功提交，删除冻结金额
        freezeService.removeById(context.getXid());
        return true;
    }

    @Override
    public boolean cancel(BusinessActionContext context) {
        //失败提交，回滚
        //将冻结金额返回到用户账户余额
        AccountFreeze freeze = freezeService.getById(context.getXid());
        if (freeze!=null) {
            LambdaUpdateWrapper<Account> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Account::getUserId,freeze.getUserId());
            wrapper.setSql("money=money+"+freeze.getFreezeMoney());
            accountService.update(wrapper);
            //删除冻结金额
            freezeService.removeById(freeze.getXid());
        }
        return true;
    }
}
